<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="活动标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入活动标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="活动开始时间" prop="startTime">
        <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择活动开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="活动状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择活动状态" clearable>
          <el-option v-for="dict in activity_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="学校" prop="schoolId">
        <el-select v-model="queryParams.schoolId" placeholder="请选择学校" clearable style="width: 100%">
          <el-option v-for="item in schools" :key="item.id" :label="item.schoolName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:activity:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Picture" @click="handleBannerList"
          v-hasPermi="['manage:activity:edit']">轮播图</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList">
      <el-table-column label="序号" align="center" prop="activityId" type="index" width="55px" />
      <el-table-column label="活动标题" align="center" prop="title" />
      <el-table-column label="活动开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="activity_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="学校" align="center" prop="schoolId">
        <template #default="scope">
          {{ getSchoolNameById(scope.row.schoolId) }}
        </template>
      </el-table-column>
      <el-table-column label="封面图" align="center" prop="coverImage" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.coverImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleEnrollList(scope.row.activityId)"
            v-hasPermi="['manage:activity:list']">报名名单</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:activity:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:activity:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改活动信息对话框 -->
    <el-dialog :title="title" v-model="open" width="650" append-to-body>
      <el-form ref="activityRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动详情描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="活动开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择活动开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择活动结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in activity_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学校" prop="schoolId">
          <el-select v-model="form.schoolId" placeholder="请选择学校" clearable style="width: 100%">
            <el-option v-for="item in schools" :key="item.id" :label="item.schoolName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="封面图URL" prop="coverImage">
          <image-upload v-model="form.coverImage" />
        </el-form-item>
        <el-form-item label="是否上轮播图" prop="isBanner">
          <el-radio-group v-model="form.isBanner">
            <el-radio :label="0">不上轮播图</el-radio>
            <el-radio :label="1">上轮播图</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="最大参与人数" prop="maxParticipants">
          <el-input v-model="form.maxParticipants" placeholder="请输入最大参与人数" />
        </el-form-item>
        <el-form-item label="当前参与人数" prop="currentParticipants">
          <el-input v-model="form.currentParticipants" placeholder="请输入当前参与人数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 轮播图列表对话框 -->
    <el-dialog title="轮播图列表" v-model="bannerOpen" width="600" append-to-body>
      <el-table :data="bannerList" v-loading="bannerLoading">
        <el-table-column label="序号" align="center" type="index" width="55px" />
        <el-table-column label="活动标题" align="center" prop="title" />
        <el-table-column label="轮播图" align="center" prop="coverImage" width="180">
          <template #default="scope">
            <image-preview :src="scope.row.coverImage" :width="120" :height="80" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="handleBannerRemove(scope.row)"
              v-hasPermi="['manage:activity:edit']">移除轮播</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="bannerOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 报名名单列表卡片 -->
    <div v-if="enrollOpen" class="enroll-container">
      <div class="enroll-card-wrapper" :class="{ 'with-detail': userDetailOpen }">
        <div class="card-header">
          <div class="title-container">
            <span class="card-title">报名名单列表</span>
            <span class="subtitle">共 {{ enrollList.length }} 条数据</span>
          </div>
          <el-button
            type="text"
            @click="handleCloseEnrollDialog"
            class="close-card-btn"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <div class="card-body">
          <el-table 
            :data="enrollList" 
            @selection-change="handleSelectionChange" 
            :max-height="350"
            stripe
            style="width: 100%;"
          >
            <el-table-column type="selection" width="40" />
            <el-table-column label="序号" align="center" type="index" width="50" />
            <el-table-column label="用户名" align="center" min-width="80">
              <template #default="scope">
                <el-button link type="primary" @click="lookUserDetail(scope.row.userId)"
                  v-hasPermi="['manage:activity:list']">{{ scope.row.userName}}</el-button>
              </template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="70">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.finish === 1">已完成</el-tag>
                <el-tag type="info" v-else>未完成</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="70">
              <template #default="scope">
                <el-button 
                  link 
                  type="primary" 
                  @click="handleUserActivityStatus(scope.row)"
                  v-hasPermi="['manage:activity:edit']"
                >
                  {{ scope.row.finish === 0 ? '完成' : '取消完成' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <div class="card-footer">
          <el-button type="primary" @click="handleBatchComplete()" :disabled="selectActivityUsers.length == 0">
            批量完成
          </el-button>
          <el-button @click="enrollOpen = false">关 闭</el-button>
        </div>
      </div>
    </div>

    <!-- 用户详情组件 - 仅在需要时渲染 -->
    <div v-if="userDetailOpen" class="user-detail-container" @click.self="closeUserDetail">
      <div class="user-detail-wrapper">
        <div class="close-button-wrapper">
          <el-button 
            type="primary" 
            circle 
            size="small" 
            @click="closeUserDetail" 
            class="close-detail-btn"
          >
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <user-detail-dialog 
          ref="userDetailRef" 
          :schools="schools" 
          @close="closeUserDetail" 
        />
      </div>
    </div>
  </div>
</template>

<script setup name="Activity">
import { listActivity, getActivity, delActivity, addActivity, updateActivity } from "@/api/manage/activity";
import { listSchool } from "@/api/manage/school";
import { changeActivityFinishBatch, getEnrollUserListByActivityId } from "../../../api/manage/activity";
import UserDetailDialog from "@/views/manage/user/components/UserDetailDialog.vue";
import { ref, reactive, toRefs, getCurrentInstance, nextTick } from 'vue';
import { Close } from '@element-plus/icons-vue';
const { proxy } = getCurrentInstance();
const { activity_status } = proxy.useDict('activity_status');

const activityList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const enrollList = ref([]);
const enrollOpen = ref(false);
const userDetailRef = ref(null);
const selectActivityUsers = ref([]);

// 轮播图相关变量
const bannerOpen = ref(false);
const bannerLoading = ref(false);
const bannerList = ref([]);

// 用户详情相关变量
const userDetailOpen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    startTime: null,
    status: null,
    schoolId: null,
  },
  rules: {
    title: [
      { required: true, message: "活动标题不能为空", trigger: "blur" }
    ],
    description: [
      { required: true, message: "活动详情描述不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "活动开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "活动结束时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "活动状态不能为空", trigger: "change" }
    ],
    schoolId: [
      { required: true, message: "学校ID不能为空", trigger: "blur" }
    ],
    location: [
      { required: true, message: "活动地点不能为空", trigger: "blur" }
    ],
    coverImage: [
      { required: true, message: "封面图URL不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/**点击报名名单按钮事件 */
function handleEnrollList(activityId) {
  getEnrollUserListByActivityId(activityId).then(response => {
    enrollList.value = response.rows;
    enrollOpen.value = true;
  });
}

/**根据学校id获取学校名称 */
function getSchoolNameById(id) {
  for (let i = 0; i < schools.value.length; i++) {
    if (schools.value[i].id == id) {
      return schools.value[i].schoolName;
    }
  }
}

/** 查询活动信息列表 */
function getList() {
  console.log(activity_status);
  loading.value = true;
  listActivity(queryParams.value).then(response => {
    activityList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    activityId: null,
    title: null,
    description: null,
    startTime: null,
    endTime: null,
    status: null,
    schoolId: null,
    isBanner: 0,
    location: null,
    coverImage: null,
    maxParticipants: null,
    currentParticipants: null,
    createdAt: null,
    updatedAt: null
  };
  proxy.resetForm("activityRef");
}
/**获取学校列表 */
const schools = ref([]);
function getSchoolList() {
  listSchool().then((response) => {
    schools.value = response.rows;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加活动信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _activityId = row.activityId || ids.value
  getActivity(_activityId).then(response => {
    const data = response.data;
    form.value = {
      ...data,
      status: String(data.status),
      isBanner: data.isBanner !== undefined ? data.isBanner : 0
    }
    open.value = true;
    title.value = "修改活动信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["activityRef"].validate(valid => {
    if (valid) {
      if (form.value.activityId != null) {
        updateActivity(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addActivity(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _activityIds = row.activityId || ids.value;
  proxy.$modal.confirm('是否确认删除活动信息编号为"' + _activityIds + '"的数据项？').then(function () {
    return delActivity(_activityIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/activity/export', {
    ...queryParams.value
  }, `activity_${new Date().getTime()}.xlsx`)
}

/** 轮播图按钮操作 */
function handleBannerList() {
  bannerLoading.value = true;
  bannerOpen.value = true;
  // 获取所有活动并筛选出isBanner=1的
  listActivity({ pageSize: 100 }).then(response => {
    bannerList.value = response.rows.filter(item => item.isBanner === 1);
    bannerLoading.value = false;
  });
}

/** 移除轮播图操作 */
function handleBannerRemove(row) {
  proxy.$modal.confirm('确定要将该活动从轮播图中移除吗？').then(() => {
    updateActivity({
      activityId: row.activityId,
      isBanner: 0
    }).then(() => {
      proxy.$modal.msgSuccess("移除轮播成功");
      handleBannerList(); // 刷新轮播图列表
      getList(); // 刷新活动列表
    });
  }).catch(() => { });
}

/** 用户活动状态操作 */
function handleUserActivityStatus(row) {
  const statusText = row.finish === 0 ? '完成' : '取消完成';
  const newStatus = row.finish === 0 ? 1 : 0;
  
  proxy.$modal.confirm(`确认将用户"${row.userName}"的活动状态设置为${statusText}吗?`).then(() => {
    changeActivityFinishBatch({activityId:row.activityId,userIds:[row.userId], finish: newStatus}).then(() => {
      proxy.$modal.msgSuccess("修改成功");
      handleEnrollList(row.activityId);
    });
  }).catch(() => {});
}

/** 批量完成操作 */
function handleBatchComplete() {
  if (selectActivityUsers.value.length == 0) {
    return;
  }
  const userIds = selectActivityUsers.value.map(au => au.userId)
  console.log(userIds);
  //确认提示
  proxy.$modal.confirm('确定要批量完成所选用户的活动吗？').then(() => {
    changeActivityFinishBatch({activityId:selectActivityUsers.value[0].activityId,userIds: userIds, finish: 1 }).then(() => {
      proxy.$modal.msgSuccess("批量完成成功");
      handleEnrollList(selectActivityUsers.value[0].activityId);
    });
  }).catch(() => {});
}

/** 选择操作 */
function handleSelectionChange(selection) {
  selectActivityUsers.value = selection;
}

/**关闭报名名单对话框 */
function handleCloseEnrollDialog() {
  enrollOpen.value = false;
  userDetailOpen.value = false;
}

/**关闭用户详情 */
function closeUserDetail() {
  userDetailOpen.value = false;
}

/**查看用户详情 */
function lookUserDetail(id) {
  if (!id) return;
  userDetailOpen.value = true;
  nextTick(() => {
    userDetailRef.value?.handleLookDetails(id);
  });
}

getList();
getSchoolList();
</script>

<style scoped>
.enroll-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  pointer-events: none;
}

.enroll-card-wrapper {
  position: absolute;
  width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
  left: calc(50% - 200px);
  top: 80px;
  pointer-events: auto;
}

.card-header {
  padding: 20px 24px 16px;
  background: linear-gradient(135deg, #4b6cb7, #182848);
  color: white;
  border-top-left-radius: 12px;
  border-top-right-radius: 12px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.title-container {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.subtitle {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.card-body {
  padding: 20px;
  max-height: 350px;
  overflow-y: auto;
}

.card-footer {
  padding: 15px 20px 20px;
  border-top: 1px solid #e6e6e6;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.close-card-btn {
  color: white;
  font-size: 16px;
}

.user-detail-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2001;
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  padding-top: 80px;
  background-color: transparent;
  pointer-events: none;
}

.user-detail-wrapper {
  position: relative;
  width: 35%;
  height: 80vh;
  max-height: 650px;
  margin-right: 10px;
  pointer-events: auto;
}

/* 当用户详情打开，调整报名卡片位置 */
.enroll-card-wrapper.with-detail {
  left: calc(64% - 420px);
}

.close-button-wrapper {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 2002;
}

.close-detail-btn {
  background-color: #409EFF;
  color: white;
}

/* 自定义用户详情在当前页面的显示样式 */
:deep(.user-detail-overlay) {
  position: static !important;
  background-color: transparent !important;
  width: 100%;
  height: 100%;
  z-index: auto;
  pointer-events: auto;
}

:deep(.user-card-container) {
  width: 100% !important;
  max-width: 100% !important;
  height: 80vh;
  max-height: 650px;
  margin: 0;
  animation: none !important;
}

:deep(.user-card) {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

:deep(.user-card-content) {
  flex: 1;
  overflow-y: auto;
}

:deep(.close-btn) {
  visibility: hidden; /* 隐藏原始关闭按钮 */
}

/* 覆盖Element Plus table样式 */
:deep(.el-table) {
  --el-table-border-color: #e0e3e9;
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 600;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #f9fafc;
}

:deep(.el-button.is-link) {
  color: #4b6cb7;
}
</style>
